﻿using CommonLib.LogOperation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;

namespace WCFLib.ExceptionExtension
{
    public class GlobalExceptionHandler : IErrorHandler
    {
        public bool HandleError(System.Exception error)
        {
            return true;
        }

        public void ProvideFault(System.Exception error, MessageVersion version, ref Message fault)
        {
            //服务器端能够获取到错误方法
            FaultMessage faultMessage = new FaultMessage();
            if (error.GetType() == typeof(GException))
            {
                var exception = (error as GException);
                faultMessage.Type = (error as GException).ExceptionType;
                faultMessage.Message = exception.Message;
                faultMessage.ErrorCode = exception.ErrorCode;

                Logger.Exception(faultMessage.Message);
            }
            else
            {
                faultMessage.Type = Enums.ExceptionType.Unknow;
                faultMessage.Message = error.ToString();
                Logger.Error(faultMessage.Message);
            }

            var ex = new FaultException<FaultMessage>(faultMessage, error.Message);
            MessageFault mf = ex.CreateMessageFault();
            fault = Message.CreateMessage(version, mf, ex.Action);
        }
    }
}
